package pl.lodz.p.pai.common;

import java.util.logging.Logger;

import javax.sql.DataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import pl.lodz.p.pai.order.db.OrderMapper;

public abstract class IbatisDaoBase {
	
	private static int[] mutex = new int[0];
	private boolean initialized = false;
	private SqlSessionFactory sqlSessionFactory;

	public IbatisDaoBase() {
		super();
	}

	protected SqlSessionFactory getSqlSessionFactory() {
		if(sqlSessionFactory==null){
			synchronized(mutex){
				if(!initialized){
					DataSource dataSource = locateDataSource();
					TransactionFactory transactionFactory = new JdbcTransactionFactory();
					Environment environment = new Environment("development", transactionFactory, dataSource);
					Configuration configuration = new Configuration(environment);
					configuration.addMapper(OrderMapper.class);
					sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
					initialized=true;
				}
			}
		}
		return sqlSessionFactory;
	}
	
	protected abstract DataSource locateDataSource();

}